<template>
  <div>
    <div style="display: flex">
      <div style="margin:10px 10px">
        <el-input style="width: 200px" placeholder="请输入名称" suffix-icon="el-icon-search" v-model="name"></el-input>
        <!--        <el-input style="width: 200px" placeholder="请输入邮箱" suffix-icon="el-icon-message" class="ml-5" v-model="email"></el-input>-->
        <el-button class=ml-5 type="primary" @click="load">搜索</el-button>
        <el-button type="warning" @click="reset">重置</el-button>
      </div>
      <div style="margin:10px 0">
        <el-button type="primary" @click="handleAdd">新增<i class="el-icon-circle-plus-outline"></i></el-button>
        <el-popconfirm
            class="ml-5"
            confirm-button-text='确定'
            cancel-button-text='取消'
            icon="el-icon-info"
            icon-color="red"
            title="您确定批量删除这些数据吗？"
            @confirm="delBatch"
        >
          <el-button type="danger" slot="reference">批量删除<i class="el-icon-remove-outline"></i></el-button>
        </el-popconfirm>
      </div>
    </div>

    <el-table :data="medicineList" border stripe header-cell-class-name="headerBg"
              @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="id" label="id" width="300" align="center"></el-table-column>
      <el-table-column prop="classid" label="药品类别" width="120" align="center">

      </el-table-column>
      <el-table-column prop="name" label="药品名" width="140" align="center"></el-table-column>
      <el-table-column prop="preprice" label="预售价" width="140" align="center"></el-table-column>

      <el-table-column prop="price" label="价格" width="140" align="center"></el-table-column>
      <el-table-column prop="picurls" label="图片" width="150" align="center">
        <template slot-scope="scope">
          <el-avatar shape="rectangle" style=" width: 50px; height: 50px" :src="scope.row.picurls"
                     :fit="'fill'"></el-avatar>
          　　
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button type="success" @click="handleEdit(scope.row)">编辑<i class="el-icon-edit"></i></el-button>
          <el-popconfirm
              class="ml-5"
              confirm-button-text='确定'
              cancel-button-text='取消'
              icon="el-icon-info"
              icon-color="red"
              title="确定删除吗？"
              @confirm="del(scope.row.id)"
          >
            <el-button type="danger" slot="reference">删除<i class="el-icon-delete"></i></el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <div style="padding: 10px 0">
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageNum"
          :page-sizes="[5, 10, 20]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>

    </div>
    <el-dialog title="药品信息" :visible.sync="dialogFormVisible" width="30%" align="center">
      <el-form label-width="80px" size="small">
        <el-form-item label="药品名">
          <el-input v-model="form.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="药品类别">
          <el-input v-model="form.classid" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="预售价">
          <el-input v-model="form.preprice" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="价格">
          <el-input v-model="form.price" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="图片">
          <input type="file" @change="handleFileUpload"/>
          <img v-if="form.picurls" :src="form.picurls" alt="Image" width="100" height="100"/>
        </el-form-item>


      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import axios from "axios";

export default {
  name: "Medicine",
  data() {
    return {
      tableData: [],
      total: 0,
      pageNum: 1,
      pageSize: "10",
      name: "",
      classid: "",
      password: "",
      email: "",
      picurls: "",
      preprice: "",
      price: "",
      id: "",
      circleUrl: "",
      dialogFormVisible: false,
      multipleSelection: [],
      form: {},
      headerBg: 'headerBg',
      medicineList: [],
    }
  },
  created() {
    /*this.load();*/
    this.load();
  },
  methods: {
    getData() {
      axios({
        method: "GET",
        url: this.$e.Url + "/product/FindAll",
      }).then((res) => {
        console.log("请求API接口【/product/FindAll】", res);
        this.medicineList = res.data;
      })
    },
    del(id) {
      axios({
        url: this.$e.Url + "/admin/checkToken",
        params: {
          Token: localStorage.getItem("Token") || ""
        },
        method: "GET"
      }).then(ans => {
        console.log("请求API接口【/admin/checkToken】", ans);
        if (ans.data.result) {
          axios.delete(this.$e.Url + "/product/DeleteProduct", {
            params: {
              id: id,
            }
          }).then((res) => {
            console.log("请求API接口【/admin/deleteUser】", res);
            if (res) {
              this.$message.success("删除成功")
            } else {
              this.$message.error("删除失败")
            }
            /*                    this.usernameList=res.data;*/
            this.load();
          })
        } else {
          this.$message.error("身份过期,权限不够");
        }
      })
    },
    load() {
      axios.get(this.$e.Url + "/product/Page", {
            params: {
              pageNum: this.pageNum,
              pageSize: this.pageSize,
              name: this.name,

            }
          }
      ).then(res => {
        console.log("/product/Page分页请求", res);
        this.medicineList = res.data.data
        for (let i = 0; i < this.medicineList.length; i++) {
          if (this.medicineList[i].classid == 0) this.medicineList[i].classid = "抗过敏";
          if (this.medicineList[i].classid == 1) this.medicineList[i].classid = "消炎药";
          if (this.medicineList[i].classid == 2) this.medicineList[i].classid = "解热镇痛";
          if (this.medicineList[i].classid == 3) this.medicineList[i].classid = "眼科用药";
          if (this.medicineList[i].classid == 4) this.medicineList[i].classid = "皮肤用药";
          if (this.medicineList[i].classid == 5) this.medicineList[i].classid = "口腔用药";
        }
        this.total = res.data.total;
        console.log("药品信息-----------", this.medicineList);
        /* this.usernameList=res.data;*/
      })
    },
    handleAdd() {
      axios({
        url: this.$e.Url + "/admin/checkToken",
        params: {
          Token: localStorage.getItem("Token") || ""
        },
        method: "GET"
      }).then(ans => {
        console.log("请求API接口【/admin/checkToken】", ans);
        if (ans.data.result) {
          this.dialogFormVisible = true
          this.form = {}
        } else {
          this.$message.error("身份过期,权限不够");
        }
      })
    },
    save() {
      axios.post(this.$e.Url + "/product/SaveProduct", {
            id: this.form.id,
            name: this.form.name,
            classid: this.form.classid,
            preprice: this.form.preprice,
            price: this.form.price,
            picurls: this.form.picurls,
          }
      ).then(res => {
        console.log("数据", res);
        if (res) {
          this.$message.success("保存成功")
          this.dialogFormVisible = false
          this.load()
        } else {
          this.$message.error("保存失败")
        }
      })
    },
    handleSelectionChange(val) {
      console.log(val)
      this.multipleSelection = val

    },
    delBatch() {
      axios({
        url: this.$e.Url + "/admin/checkToken",
        params: {
          Token: localStorage.getItem("Token") || ""
        },
        method: "GET"
      }).then(ans => {
        console.log("请求API接口【/admin/checkToken】", ans);
        if (ans.data.result) {
          let ids = this.multipleSelection.map(v => v.id)  // 获取所有需要删除的id
          let deletePromises = ids.map(id => {  // 将每个删除操作转换为一个Promise
            return axios.delete(this.$e.Url + "/product/DeleteProduct", {
              params: {
                id: id,
              }
            });
          });
          console.log("删除信息", deletePromises)
          Promise.all(deletePromises).then(responses => {  // 等待所有删除操作完成
            // 检查所有删除操作的响应，如果有任何一个响应表示删除失败，则认为批量删除失败
            let success = responses.every(response => response.status === 200);
            if (success) {
              this.$message.success("批量删除成功");
            } else {
              this.$message.error("批量删除失败");
            }
            this.load();
          });
        } else {
          this.$message.error("身份过期,权限不够");
        }
      })
    },
    handleEdit(row) {
      axios({
        url: this.$e.Url + "/admin/checkToken",
        params: {
          Token: localStorage.getItem("Token") || ""
        },
        method: "GET"
      }).then(ans => {
        console.log("请求API接口【/admin/checkToken】", ans);
        if (ans.data.result) {
          this.form = row
          this.dialogFormVisible = true
        } else {
          this.$message.error("身份过期,权限不够");
        }
      })
    },
    handleFileUpload(event) {
      console.log("选择图片上传--------------请求接口", this.$e.Url + "Files/upload");
      let file = event.target.files[0];
      let formData = new FormData();
      formData.append('file', file);
      axios.post(this.$e.Url + '/Files/upload', formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      }).then(response => {
        console.log("-----------------图片上传", response);
        // 这里假设服务器在文件上传成功后，返回的`data`对象中包含了上传文件的URL。
        // 根据你实际情况修改
        if (response.data.code === '1') { // 假设 'string' 是成功的代码
          this.form.picurls = response.data.result; // 假设 fileUrl 是返回的图片链接【】
        } else {
          console.error('Upload failed:', response.data.message);
        }
      }).catch(error => {
        console.error(error);
      });
    },
    reset() {
      this.name = ""
      this.load()
    },
    handleSizeChange(pageSize) {
      console.log(pageSize)
      this.pageSize = pageSize
      this.load()
    },
    handleCurrentChange(pageNum) {
      console.log(pageNum)
      this.pageNum = pageNum
      this.load()
    }
  }
}
</script>

<style>
.headerBg {
  background: #cccccc !important;

}
</style>
